#include "iot_errno.h"
#include "iot_gpio.h"
#include "rtthread.h"
#include "rtdevice.h"


unsigned int IoTGpioInit(unsigned int id)
{
    return IOT_SUCCESS;
}

unsigned int IoTGpioDeinit(unsigned int id)
{
    return IOT_SUCCESS;
}

unsigned int IoTGpioSetDir(unsigned int id, IotGpioDir dir)
{
    rt_base_t pin = id;
    rt_base_t mode = 0;

    mode = (IOT_GPIO_DIR_IN == dir) ? PIN_MODE_INPUT : PIN_MODE_OUTPUT;
    rt_pin_mode(pin, mode);

    return IOT_SUCCESS;
}

unsigned int IoTGpioGetDir(unsigned int id, IotGpioDir *dir)
{
    return IOT_SUCCESS;
}

unsigned int IoTGpioSetOutputVal(unsigned int id, IotGpioValue val)
{
    rt_base_t pin = id;
    rt_base_t value = 0;

    value = (IOT_GPIO_VALUE0 == val) ? PIN_LOW : PIN_HIGH;
    rt_pin_write(pin, value);

    return IOT_SUCCESS;
}

unsigned int IoTGpioGetOutputVal(unsigned int id, IotGpioValue *val)
{
    rt_base_t pin = id;
    rt_base_t value = 0;

    value = rt_pin_read(pin);
    *val = value;

    return IOT_SUCCESS;
}

unsigned int IoTGpioGetInputVal(unsigned int id, IotGpioValue *val)
{
    rt_base_t pin = id;
    rt_base_t value = 0;

    value = rt_pin_read(pin);
    *val = value;

    return IOT_SUCCESS;
}


unsigned int IoTGpioRegisterIsrFunc(unsigned int id, IotGpioIntType intType, IotGpioIntPolarity intPolarity,
                                    GpioIsrCallbackFunc func, char *arg)
{
    rt_base_t pin = id;
    rt_base_t mode = 0;

    if(IOT_INT_TYPE_LEVEL == intType && IOT_GPIO_EDGE_FALL_LEVEL_LOW == intPolarity)
    {
        mode = PIN_IRQ_MODE_LOW_LEVEL;
    }
    else if(IOT_INT_TYPE_LEVEL == intType && IOT_GPIO_EDGE_RISE_LEVEL_HIGH == intPolarity)
    {
        mode = PIN_IRQ_MODE_HIGH_LEVEL;
    }
    else if(IOT_INT_TYPE_EDGE == intType && IOT_GPIO_EDGE_FALL_LEVEL_LOW == intPolarity)
    {
        mode = PIN_IRQ_MODE_FALLING;
    }
    else if(IOT_INT_TYPE_EDGE == intType && IOT_GPIO_EDGE_RISE_LEVEL_HIGH == intPolarity)
    {
        mode = PIN_IRQ_MODE_RISING;
    }

    rt_pin_attach_irq(pin, mode, func, (void *)arg);

    return IOT_SUCCESS;
}

unsigned int IoTGpioUnregisterIsrFunc(unsigned int id)
{
    rt_err_t err = RT_EOK;
    rt_base_t pin = id;

    err = rt_pin_detach_irq(pin);
    if(err != RT_EOK)
    {
        return IOT_FAILURE;
    }

    return IOT_SUCCESS;
}

unsigned int IoTGpioSetIsrMask(unsigned int id, unsigned char mask)
{
    rt_base_t pin = id;

    rt_pin_irq_enable(pin, (rt_uint32_t)mask);

    return IOT_SUCCESS;
}

unsigned int IoTGpioSetIsrMode(unsigned int id, IotGpioIntType intType, IotGpioIntPolarity intPolarity)
{

    return IOT_SUCCESS;
}


